package Gui.Dialogs;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.GridLayout;
import java.util.ArrayList;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;

import Gui.GameFrame;
import Main.Defines;
import PlayerManager.Player;

public class GameOverStatsDialog extends JDialog {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4574325626658275519L;
	private JPanel m_jp;
	private void buildUIContents() {
		JLabel infoLabel = new JLabel();
		String infoString = "";
		infoString += "<html>";
		ArrayList<Integer> winningPlayerIDS = new ArrayList<Integer>();
		int winningScore = Integer.MIN_VALUE;
		// add players to label and check for winner
		for (int i = 0; i < Defines.PLM.getPlayerList().size(); ++i){
			Player player = Defines.PLM.getPlayerList().get(i);
			infoString += player.getGameOverToString();
			// if current Score is less than winningScore, winningPlayers list,
			// add this player, update winningScore
			if (winningScore < player.getCash() - player.getLoan()) {
				winningPlayerIDS = new ArrayList<Integer>();
				winningPlayerIDS.add(i);
				winningScore = player.getCash() - player.getLoan();
			} else if (winningScore == player.getCash() - player.getLoan()) {
				// there is a tie for best score
				winningPlayerIDS.add(i);
			}
			infoString += "<br>";
		}
		infoString +=  "<br>";
		// print winning players
		for( int i : winningPlayerIDS){
			infoString += "Player " + (i + 1);
			// add " and" string if the winningPlayers list is greater than 0 and is not the last winner in the list
			if(winningPlayerIDS.size() > 2  && i < winningPlayerIDS.size() - 2)
				infoString += ", <br>";
			else if(winningPlayerIDS.size() > 0 && i < winningPlayerIDS.size() - 1){
				infoString += (winningPlayerIDS.size() > 2?",":"") + " and <br>";
			}
			
		}
		infoString += " won!!";
		infoLabel.setText(infoString);
		m_jp.add(infoLabel);
	}

	public GameOverStatsDialog() {
		//super(GameFrame.getInstance(), "Event", true);
		m_jp = new JPanel(new GridLayout(0, 2));
		m_jp.setBorder(Defines.getEmptyBorderConstraints());
		setModalityType(getModalityType().APPLICATION_MODAL);
		setLayout(new BorderLayout());
		buildUIContents();
		add(m_jp, BorderLayout.CENTER);
		pack();
		
		if(getTitle() != null){
			FontMetrics fm = getFontMetrics(getFont());
			int width = fm.stringWidth(getTitle()) + Defines.ICON_WIDTH;
			width = (int) Math.max(width*1.2, getPreferredSize().getWidth());
			setSize(new Dimension(width, getHeight()));
		}
		setLocationRelativeTo(GameFrame.getInstance());
		setVisible(true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	}
}
